package com.hualude.roadsign.service.impl;

import com.hualude.roadsign.dto.*;
import com.hualude.roadsign.repository.*;
import com.hualude.roadsign.service.MonitorFaultService;
import com.hualude.roadsign.utils.PushUtil;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * Created by pjn on 2017/8/5.
 */
@Service
public class MonitorFaultServiceImpl implements MonitorFaultService {
    @Resource
    private MonitorFaultRepository monitorFaultRepository;
    @Resource
    private MonitorRepository monitorRepository;
    @Resource
    private UserRepository userRepository;
    @Resource
    private OrgRepository orgRepository;
    @Resource
    private PushHistoryRepository pushHistoryRepository;

    private String strUserIds;

    private SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public DTResponseDto getMonitorReportFault4DT(DTRequestDto dtRequestDto, Integer actorId, Integer userId, Integer orgId) throws Exception {
        Integer count;
        List<DTMonitorFaultDto> dto4DTs;
        count = monitorFaultRepository.getMonitorReportFaultCount4DT(actorId, userId, orgId, dtRequestDto.getSearch());
        dto4DTs = monitorFaultRepository.getMonitorReportFault4DT(dtRequestDto, actorId, userId, orgId);
        for (DTMonitorFaultDto dto : dto4DTs) {
            dto.setMonitorCheckerName(userRepository.getUserNameByUserId(dto.getMonitorCheckerId()));
        }
        DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), count, count, dto4DTs);
        return dtResponseDto;
    }

    @Transactional
    public Integer updateMonitorFault(Integer monitorFaultId, Integer monitorFaultLevel, Integer monitorFaultType, String monitorFaultPhoto, String monitorFaultReason, Double monitorMoney) throws Exception {
        return monitorFaultRepository.updateMonitorFault(monitorFaultId, monitorFaultLevel, monitorFaultType, monitorFaultPhoto, monitorFaultReason, monitorMoney);
    }

    @Transactional
    public Integer deleteMonitorFaultByIds(String monitorFaultIds) throws Exception {
        String[] faultIdArray = monitorFaultIds.split(",");
        int i = 0;
        for (i = 0; i < faultIdArray.length; i++) {
            monitorFaultRepository.deleteMonitorFaultByIds(Integer.parseInt(faultIdArray[i]));
        }
        return i;
    }

    public List<MonitorFaultDto> getMonitorCoordinate4Map(Integer orgId, Integer actorId) throws Exception {
        return monitorRepository.getMonitorCoordinate4Map(orgId, actorId);
    }

    public List<MonitorFaultDto> getMonitorEnergyByXY(String longitude, String latitude) throws Exception {
        return monitorRepository.getMonitorEnergyByXY(longitude, latitude);
    }


    public Integer reportMonitorFault(final Integer monitorId, Integer monitorFaultCreatorId, Integer monitorFaultLevel, Integer monitorFaultType,
                                      String monitorFaultPhoto, String monitorFaultReason, Double monitorMoney, final Integer monitorOrgId, Integer monitorMainOrgId) throws Exception {
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        if (monitorMoney == null)
            monitorMoney = 0.0;
        MonitorFaultDto insertDto = new MonitorFaultDto();
        insertDto.setMonitorId(monitorId);
        insertDto.setMonitorFaultCreatorId(monitorFaultCreatorId);
        insertDto.setMonitorFaultLevel(monitorFaultLevel);
        insertDto.setMonitorFaultType(monitorFaultType);
        insertDto.setMonitorFaultTime(df.format(new Date()));
        insertDto.setMonitorFaultPhoto(monitorFaultPhoto);
        insertDto.setMonitorFaultReason(monitorFaultReason);
        insertDto.setMonitorMoney(monitorMoney);
        insertDto.setMonitorOrgId(monitorOrgId);
        insertDto.setMonitorMainOrgId(monitorMainOrgId);

        List<UserDto> userDtos = userRepository.getUserIdsByOrgIdAndActorId(monitorOrgId, 3);
        final String msg = "监控箱 NO：" + monitorId + " 待审核";
        strUserIds = "";
        for (UserDto userDto : userDtos) {
            strUserIds += userDto.getUserId().toString() + ",";
        }
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    if (!strUserIds.equals("")) {
                        strUserIds = strUserIds.substring(0, strUserIds.length() - 1);
                        PushUtil.sendPushToUser(strUserIds, msg);
                        PushHistoryDto pushHistoryDto = new PushHistoryDto(monitorOrgId, 3, msg, formatter.format(new Date()),8);
                        pushHistoryRepository.save(pushHistoryDto.toBean());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();

        return monitorFaultRepository.save(insertDto.toBean()).getMonitorFaultId();
    }

    public Integer getMonitorFaultIsReport(Integer monitorId) throws Exception {
        List<MonitorFaultDto> monitorFaultDtos = monitorFaultRepository.getMonitorFaultIsReport(monitorId);
        Integer result = 1;
        if (monitorFaultDtos.size() != 0) {
            Integer mainCheck = monitorFaultDtos.get(0).getMonitorMainCheck();
            Integer check = monitorFaultDtos.get(0).getMonitorCheck();
            Integer status = monitorFaultDtos.get(0).getMonitorMaintenanceStatus();
            if (status == 2) {
                result = 1;//维修完成
            } else if (mainCheck == -1 || check == -1) {
                result = 1;//
            } else {
                result = 0;
            }
        }
        return result;
    }

    public DTResponseDto getMonitorFaultReport4DT(DTRequestDto dtRequestDto, Integer actorId, Integer orgId, String roadName, String startRoad, String endRoad) throws Exception {
        if (roadName.equals("") && startRoad.equals("") && endRoad.equals("")) {
            return new DTResponseDto(dtRequestDto.getDraw(), 0, 0, "");
        } else {
            List<DTMonitorFaultDto> dto4DTs = monitorRepository.getMonitorFaultReport4DT(dtRequestDto, actorId, orgId, roadName, startRoad, endRoad);
            for (DTMonitorFaultDto dto : dto4DTs) {
                List<MonitorFaultDto> monitorFaultDtos = monitorFaultRepository.getMonitorFaultIsReport(dto.getMonitorId());
                Integer result = 1;
                if (monitorFaultDtos.size() != 0) {
                    Integer mainCheck = monitorFaultDtos.get(0).getMonitorMainCheck();
                    Integer check = monitorFaultDtos.get(0).getMonitorCheck();
                    Integer status = monitorFaultDtos.get(0).getMonitorMaintenanceStatus();
                    if (status == 2) {
                        result = 1;//维修完成
                    } else if (mainCheck == -1 || check == -1) {
                        result = 1;//
                    } else {
                        result = 0;
                    }
                }
                dto.setReportStatus(result);
            }
            DTResponseDto dtResponseDto = new DTResponseDto(dtRequestDto.getDraw(), 1, 1, dto4DTs);
            return dtResponseDto;
        }
    }

}
